package com.fitness.util.interceptor;

import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.fitness.util.JsonUtil;

public class MyExceptionHandler implements HandlerExceptionResolver {
	
	private static final Logger log = LoggerFactory.getLogger(MyExceptionHandler.class);
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		response.setContentType("application/json;charset=utf-8");
		 String result = "";
		 log.error("报告了一个错误:"+request.getRequestURL()+"错误信息为"+ex.getMessage());
		if(ex instanceof java.lang.NullPointerException) result = JsonUtil.blank(false,500,"数据传入为空");
		if(ex instanceof SQLIntegrityConstraintViolationException)result = JsonUtil.blank(false,500,"重复数据");
		if(ex instanceof SQLException)result = JsonUtil.blank(false,500,"数据处理异常");
		else  result = JsonUtil.blank(false,400,"未知错误");
		try {
			response.getWriter().print(result);
		} catch (IOException e){
			e.printStackTrace();
			ModelAndView mv =  new ModelAndView();
			mv.setViewName("error");
			return mv;
		}
		return null;
	}


	
}
